package com.atguigu.watermark.wait;

import com.atguigu.bean.WaterSensor;
import com.atguigu.function.WaterSensorMapFunction;
import com.atguigu.partition.MyPartitioner;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 等待分区数据倾斜设置
 */
public class WatermarkIdlenessDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);


        SingleOutputStreamOperator<Integer> sensorDS = env
                .socketTextStream("10.75.186.206", 9999)
                // 自定义分区器：数据%分区数，只输入奇数，都只会去往map的一个子任务
                .partitionCustom(new MyPartitioner(), i -> i)
                .map(Integer::parseInt);

        sensorDS.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Integer>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<Integer>() {
                            @Override
                            public long extractTimestamp(Integer integer, long l) {
                                return integer * 1000L;
                            }
                        })
                        // 如果不设置，一直录入奇数，则会一直等待偶数子任务，不会关窗
                        // 空闲等待5s  超过5s当前子任务（并行度）无数据，则不会继续等待
                        .withIdleness(Duration.ofSeconds(5))
        )
                .keyBy(i -> i % 2)        // 分成两组： 奇数一组，偶数一组 ， 开10s的事件时间滚动窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .process(new ProcessWindowFunction<Integer, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer s, ProcessWindowFunction<Integer, String, Integer, TimeWindow>.Context context, Iterable<Integer> elements, Collector<String> out) throws Exception {
                        long startTs = context.window().getStart();
                        long endTs = context.window().getEnd();
                        String windowStart = DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss.SSS");

                        long count = elements.spliterator().estimateSize();

                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());

                    }
                })
                .print();

        env.execute();
    }

}
